package org.amj.wn.admin.analytics;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.amj.wn.WaqfeNau;

import com.google.appengine.api.datastore.Entity;

class AnalyticsCache implements Serializable {

	private static final long serialVersionUID = -663868093446387886L;
	
	private long lastUpdated = 0;
	private static final long updateInterval = 1000 * 60 * 60 * 3;
	private Table table;
	
	private AnalyticsCache() {}
	
	private static AnalyticsCache instance = new AnalyticsCache();
	
	public static AnalyticsCache getInstance() {
		return instance;
	}

	public Table getTable() {
		rebuild();
		return table;
	}

	private synchronized void rebuild() {
		
		if(!shouldRebuild())
			return;
		
		boolean hasMore = true;
		int startIndex = 0;
		int pageSize = 20;
		table = null;
		table = new Table();
		List<Entity> totalList = new ArrayList<Entity>();
		while(hasMore) {
			List<Entity> result = WaqfeNau.search(startIndex, pageSize, null, null, null, null, null, null);
			if(result.size() > 0) {
				totalList.addAll(result);
			}
			
			hasMore = result.size() == pageSize;
			startIndex = startIndex + pageSize;
			
		}
		
		table.setRows(totalList);
		lastUpdated = System.currentTimeMillis();
	}


	private boolean shouldRebuild() {
		return System.currentTimeMillis() - lastUpdated > updateInterval;
	}

	public long getLastUpdated() {
		return lastUpdated;
	}
	
}
